<!--
 * @Descripttion: 通用词库管理
 * @version: V1.0.0.0
 * @Author: Converted to Vue3 + TypeScript
 * @Date: 2025-10-14
-->
<template>
	<div class="common-words-manage-page">
		<div class="manage-layout search-wrapper">
			<div class="title-wrapper">
				<span class="title">通用词筛选</span>
			</div>
			<div class="content-wrapper">
				<div class="filter-item">
					<span class="item-label">通用词</span>
					<el-input
						class="item-input"
						v-model="queryObj.searchValue"
						placeholder="输入通用词类型或常用语名称搜索"
						clearable
						@change="onSearchHandle"
					/>
				</div>
				<div class="search-btn" @click="onSearchHandle">筛选</div>
				<div class="btns-wrapper">
					<div class="btn-item add-btn" @click="onAddHandle">添加</div>
					<div class="btn-item del-btn" @click="onBatchDeleteHandle">批量删除</div>
				</div>
			</div>
		</div>
		<div class="manage-layout data-wrapper">
			<div class="title-wrapper">
				<span class="title">通用词列表</span>
			</div>
			<!-- 表格 -->
			<div class="table-wrapper">
				<el-table
					:data="tableData"
					stripe
					fit
					class="self-stripe-table"
					height="100%"
					@selection-change="onSelectionChangeHandle"
				>
					<el-table-column type="selection" align="center" width="80px" />
					<el-table-column label="通用词类型" align="left" min-width="20%">
						<template #default="{ row }">
							{{ row?.typeName ?? '--' }}
						</template>
					</el-table-column>
					<el-table-column label="常用语列表" align="left" min-width="65%">
						<template #default="{ row }">
							<span v-html="row?.names ?? '--'"></span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="15%">
						<template #default="scope">
							<el-button class="table-btn" type="text" @click="onEditHandle(scope.row)"
								>修改</el-button
							>
							<el-button class="table-btn" type="text" @click="onDeleteHandle(scope.row.typeId)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<!-- 分页 -->
		<div v-if="pagination.totalPages > 1" class="pagination-wrapper">
			<el-pagination
				:current-page="pagination.currentPage"
				:total="pagination.totalCount"
				:page-size="pagination.numPerPage"
				background
				:hide-on-single-page="true"
				@current-change="onCurrentPageChangeHandle"
			/>
		</div>

		<!-- 添加修改弹框 -->
		<el-dialog
			class="self-dialog"
			v-model="dialogVisible"
			:title="dialogType === 'add' ? '添加通用词' : '修改通用词'"
			:close-on-click-modal="false"
			width="50%"
			@close="resetAddForm"
		>
			<el-form ref="ruleFormRef" :model="addForm" :rules="rules" label-width="80px">
				<el-form-item label="类型" prop="typeName">
					<el-input v-model="addForm.typeName" />
				</el-form-item>
				<el-form-item label="常用语" prop="scribeList">
					<div class="scribe-tags-wrapper">
						<el-tag
							v-for="item in addForm.scribeList"
							:key="item.name"
							closable
							:disable-transitions="false"
							@close="closeTag(item)"
						>
							{{ item.name }}
						</el-tag>
						<el-input
							v-if="inputVisible"
							ref="saveTagInputRef"
							v-model="inputValue"
							class="input-new-tag"
							size="small"
							@keyup.enter="handleInputConfirm"
							@blur="handleInputConfirm"
						/>
						<el-button v-else class="button-new-tag dark" size="small" @click="showInput">
							+ 添加知识点
						</el-button>
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCloseDialogHandle">取消</el-button>
					<el-button type="primary" @click="onConfirmHandle">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElForm, ElInput } from 'element-plus';
import {
	PaginationType,
	getErrorMessage,
	FormInstanceType,
	InputInstanceType,
	getLibCommonSlangSortByTypeAPI,
	delLibCommonSlangTypeAPI,
	addLibCommonSlangTypeAPI,
	addLibCommonSlangAPI,
	getLibCommonSlangAPI,
	delLibCommonSlangAPI
} from '@/api/index';
import { TableRowData, FormData, ScribeItem } from './LibManage.type';
/**
 * 查询通用词库数据
 */
const tableData = ref<TableRowData[]>([]);
const queryObj = ref({
	searchValue: ''
});
const pagination = reactive<PaginationType>({
	currentPage: 1,
	numPerPage: 20,
	totalCount: 0,
	totalPages: 0
});

const getLibCommonSlangSortByType = async (): Promise<void> => {
	try {
		const res = await getLibCommonSlangSortByTypeAPI({
			searchValue: queryObj.value.searchValue,
			pageNum: pagination.currentPage,
			pageSize: pagination.numPerPage
		});

		// 高亮搜索内容
		res?.list?.forEach((item: TableRowData) => {
			if (queryObj.value.searchValue) {
				// g代表全局匹配，i代表忽略大小写
				const reg = new RegExp(queryObj.value.searchValue, 'gi');
				// 这里的$&代表匹配的子串文本，在文本前后加上mark标签
				item.names = item.names?.replace(reg, `<mark>$&</mark>`);
			}
		});

		tableData.value = res.list;
		pagination.currentPage = res.currentPage;
		pagination.numPerPage = res.numPerPage;
		pagination.totalCount = res.totalCount;
		pagination.totalPages = res.totalPages;
	} catch (error) {
		ElMessage.error(getErrorMessage(error));
	}
};
// 模糊搜索
const onSearchHandle = (): void => {
	pagination.currentPage = 1;
	getLibCommonSlangSortByType();
};
// 切换页码
const onCurrentPageChangeHandle = (currentPage: number): void => {
	pagination.currentPage = currentPage;
	getLibCommonSlangSortByType();
};
onMounted(() => {
	getLibCommonSlangSortByType();
});

/**
 * 删除常用语
 */
const onDeleteHandle = (typeId: number): void => {
	ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			try {
				await delLibCommonSlangTypeAPI(String(typeId));
				ElMessage({
					type: 'success',
					message: '删除成功'
				});
				pagination.currentPage = 1;
				getLibCommonSlangSortByType();
			} catch (error) {
				ElMessage.error(getErrorMessage(error));
			}
		})
		.catch(() => {
			// 用户取消
		});
};

// 批量删除常用语
// 当前选中的列表
const selectionList = ref<TableRowData[]>([]);
// 选中项改变触发的事件
const onSelectionChangeHandle = (selection: TableRowData[]): void => {
	selectionList.value = selection;
};
const onBatchDeleteHandle = (): void => {
	if (!selectionList.value.length) {
		ElMessage({
			type: 'warning',
			message: '最少选择一项'
		});
		return;
	}

	ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			try {
				const ids = selectionList.value.map((item) => item.typeId).join(',');
				await delLibCommonSlangTypeAPI(ids);
				ElMessage({
					type: 'success',
					message: '删除成功'
				});
				pagination.currentPage = 1;
				getLibCommonSlangSortByType();
			} catch (error) {
				ElMessage.error(getErrorMessage(error));
			}
		})
		.catch(() => {
			// 用户取消
		});
};

/**
 * 添加或修改通用词
 */
const ruleFormRef = ref<FormInstanceType>(null);
const dialogType = ref<'add' | 'edit'>('add');
const dialogVisible = ref<boolean>(false);
// 表单数据
const addForm = ref<FormData>({
	typeName: '',
	scribeList: []
});
// 表单验证规则
const rules = {
	typeName: [{ required: true, message: '请输入类型名', trigger: 'blur' }],
	scribeList: [{ required: true, message: '请输入常用语', trigger: 'blur' }]
};
// 添加
const onAddHandle = (): void => {
	dialogType.value = 'add';
	dialogVisible.value = true;
};

// 修改
const currentTypeId = ref<number | null>(null);
const onEditHandle = async (row: TableRowData): Promise<void> => {
	dialogType.value = 'edit';
	dialogVisible.value = true;

	// 此次修改新增的tag列表
	addTagList.value = [];
	// 此次修改减少的tag列表
	deleteTagList.value = [];
	// 当前修改的课程库id
	currentTypeId.value = row.typeId;

	const res = await getLibCommonSlangAPI(row.typeId);

	// 展示的tag列表
	addForm.value.scribeList = [];
	res.forEach((item: any) => {
		addForm.value.scribeList.push({
			count: 1,
			name: item.name,
			id: item.id
		});
	});
	addForm.value.typeName = row.typeName;
};

// 重置添加表单
function resetAddForm() {
	addForm.value = {
		typeName: '',
		scribeList: []
	};
	ruleFormRef.value?.clearValidate();
}

// 关闭弹窗
const onCloseDialogHandle = (): void => {
	dialogVisible.value = false;
	resetAddForm();
};

// 确定弹框
const onConfirmHandle = (): void => {
	ruleFormRef.value?.validate((valid: boolean) => {
		if (valid) {
			if (dialogType.value === 'add') {
				onAddSubmitHandle();
			} else {
				onEditSubmitHandle();
			}
		}
	});
};

// 添加时提交
const onAddSubmitHandle = async (): Promise<void> => {
	try {
		// 添加课程库
		const res = await addLibCommonSlangTypeAPI({
			list: [
				{
					name: addForm.value.typeName
				}
			]
		});

		// 添加知识点
		const list = addForm.value.scribeList.map((item) => ({
			name: item.name,
			typeId: res?.[0]?.id
		}));
		await addLibCommonSlangAPI({ list });

		ElMessage({
			type: 'success',
			message: '添加成功'
		});

		getLibCommonSlangSortByType();
		resetAddForm();
		dialogVisible.value = false;
	} catch (error) {
		ElMessage.error(getErrorMessage(error));
	}
};

// 修改时提交
const onEditSubmitHandle = async (): Promise<void> => {
	try {
		// 添加通用词库类型
		const res = await addLibCommonSlangTypeAPI({
			list: [
				{
					id: currentTypeId.value,
					name: addForm.value.typeName
				}
			]
		});

		// 添加知识点
		if (addTagList.value.length) {
			const list = addTagList.value.map((item) => ({
				name: item.name,
				typeId: res?.[0]?.id
			}));
			await addLibCommonSlangAPI({ list });
		}

		// 删除常用语
		if (deleteTagList.value.length) {
			const ids = deleteTagList.value.map((item) => item.id).join(',');
			await delLibCommonSlangAPI(ids);
		}

		ElMessage({
			type: 'success',
			message: '修改成功'
		});
		getLibCommonSlangSortByType();
		resetAddForm();
	} catch (error) {
		ElMessage.error(getErrorMessage(error));
	}
};

/**
 * 常用语操作
 */

const saveTagInputRef = ref<InputInstanceType>();
// tag输入框
const inputVisible = ref<boolean>(false);
// tag输入框的值
const inputValue = ref<string>('');
// 新增的tag列表
const addTagList = ref<ScribeItem[]>([]);
// 删除的tag列表
const deleteTagList = ref<ScribeItem[]>([]);

// 显示tag输入框
const showInput = (): void => {
	inputVisible.value = true;
	nextTick(() => {
		saveTagInputRef.value?.focus();
	});
};

// 将输入的tag添加到tag列表
const handleInputConfirm = (): void => {
	const value = inputValue.value;
	if (value) {
		addForm.value.scribeList.push({ name: value, count: 1 });
		addTagList.value.push({ name: value, count: 1 });
	}
	inputVisible.value = false;
	inputValue.value = '';
};
const closeTag = (tag: ScribeItem): void => {
	if (tag.id) {
		// 如果删除的是有id的tag，则该tag是原有的tag
		deleteTagList.value.push(tag);
	} else {
		// 如果删除的tag没有id，则该tag是新增的tag
		const index = addTagList.value.findIndex((item) => item.name === tag.name);
		if (index > -1) {
			addTagList.value.splice(index, 1);
		}
	}
	const formIndex = addForm.value.scribeList.findIndex((item) => item.name === tag.name);
	if (formIndex > -1) {
		addForm.value.scribeList.splice(formIndex, 1);
	}
};
</script>

<style lang="scss" scoped>
.common-words-manage-page {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.search-wrapper {
	.search-item {
		.item-input {
			width: 25rem;
		}
	}
}

// 分页区域样式
.pagination-wrapper {
	flex-shrink: 0;
}
</style>
